package resources;

import java.util.LinkedList;
import main.Lists;
import processes.Process;

/**
 *
 * @author Ramunas
 */
public class ResPrimitives {
    
    private static int id = 0;
    
    private static int getUniqueId(){
        id++;
        return id;
    }
    
    public static Resource createResource(String name, Process creator){
        Resource resource = new Resource();
 
        resource.setName(name); //nustatomas isorinis vardas          
        resource.setId(getUniqueId()); //nustatomas vidinis vardas
        resource.setCreatorName(creator.getName()); //nustatomas isorinis kurejo vardas
        resource.setCreatorId(creator.getId()); //nustatomas vidinis kurejo vardas
        creator.addCreatedResource(resource);
        Lists.getResources().add(resource);
        return resource;
    }
    
    public static void destroyResource(Resource resource){
        LinkedList<Integer> waitingProcesses = resource.getWaitingProcesses();
        for(Integer procId: waitingProcesses){
            Lists.getProcessById(procId).setState("Pasiruoses");
        }
        Lists.getProcessById(resource.getCreatorId())
                .removeCreatedResource(resource);
        Lists.getResources().remove(resource);
    }
    
    public static void requestResource(Resource resource, Process process){
        process.setState("Blokuotas");
        if(resource != null){                            
            resource.addWaitingProcesses(process.getId());
            resource.setRequired(process.getName());
            resource.distributeResource();
        }
    }
    
    public static void freeResource(Resource resource){
        resource.distributeResource();
    }
    
    public static Resource findResource(String name){
        for(Resource res: Lists.getResources()){
            if(res.getName().equals(name)){
                return res;
            }
        }
        return null;
    }
    
}
